package com.wangzeqi.changliaoba.messege;

import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;

import com.easemob.EMCallBack;
import com.easemob.chat.EMChatManager;
import com.easemob.chat.EMConversation;
import com.easemob.chat.EMMessage;
import com.easemob.chat.TextMessageBody;
import com.wangzeqi.changliaba.dao.ChatInformation;
import com.wangzeqi.changliaba.dao.ContactsEntity;
import com.wangzeqi.changliaba.dao.ContactsEntityDao;
import com.wangzeqi.changliaoba.R;
import com.wangzeqi.changliaoba.base.BaseActivity;
import com.wangzeqi.changliaoba.contacts.CharacterParser;
import com.wangzeqi.changliaoba.contacts.SortModel;
import com.wangzeqi.changliaoba.singleton.AllSingleTon;

import java.util.ArrayList;
import java.util.List;

import de.greenrobot.dao.query.QueryBuilder;

/**
 * Created by dllo on 16/3/4.
 */
public class ForwardActivity extends BaseActivity implements View.OnClickListener {
    private ListView friendsList;
    private ForwardListViewAdapter adapter;
    private ArrayList<SortModel> data;
    private Button forwardSendBtn;
    private CharacterParser characterParser = CharacterParser.getInstance();
    private ArrayList<String> friendNames = new ArrayList<>();
    private static MyClick myClick;

    public static void setMyClick(MyClick myClick) {
        ForwardActivity.myClick = myClick;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_zhuanfa);
        friendsList = (ListView) findViewById(R.id.zhuanfa_country_lvcountry);
        forwardSendBtn = (Button) findViewById(R.id.zhuanfa_forwardsend);
        forwardSendBtn.setOnClickListener(this);
        init();
        adapter = new ForwardListViewAdapter(this, data);
        Log.d("ForwardActivity", "data.size():" + data.size());
        friendsList.setAdapter(adapter);
        adapter.updateListView(data);

    }
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.zhuanfa_forwardsend:
                Intent intent = getIntent();
                final String messege = intent.getStringExtra("zhuanfa_messege");
                for (int i = 0; i < adapter.getStates().size(); i++) {
                    if (adapter.getStates().get(i)) {
                        sendMessege(messege, friendNames.get(i));
                    }
                }
                myClick.ForwardMessegeChanged();

//                IntentFilter intentFilter = new IntentFilter();
//                intentFilter.addAction("SEND_MESSEGE_SUCCESE");
//                registerReceiver(new ChatActivity().ForwardMessegeChanged, intentFilter);
//                Intent sendIntent = new Intent("SEND_MESSEGE_SUCCESE");
//                sendBroadcast(sendIntent);
                finish();
                Toast.makeText(this, "发送成功", Toast.LENGTH_SHORT).show();
                break;
        }
    }

    private List<SortModel> filledData(String[] date) {
        List<SortModel> mSortList = new ArrayList<SortModel>();

        for (int i = 0; i < date.length; i++) {
            SortModel sortModel = new SortModel();
            sortModel.setName(date[i]);
            //汉字转换成拼音
            String pinyin = characterParser.getSelling(date[i]);
            String sortString = pinyin.substring(0, 1).toUpperCase();

            // 正则表达式，判断首字母是否是英文字母
            if (sortString.matches("[A-Z]")) {
                sortModel.setSortLetters(sortString.toUpperCase());
            } else {
                sortModel.setSortLetters("#");
            }

            mSortList.add(sortModel);
        }
        return mSortList;

    }
    //发消息
    private void sendMessege(final String messege, final String username) {
        EMConversation conversation = EMChatManager.getInstance().getConversation(username);
        final EMMessage message = EMMessage.createSendMessage(EMMessage.Type.TXT);
        TextMessageBody txtBody = new TextMessageBody(messege);
        message.addBody(txtBody);
        message.setReceipt(username);
        conversation.addMessage(message);

        EMChatManager.getInstance().sendMessage(message, new EMCallBack() {
            @Override
            public void onSuccess() {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        AllSingleTon.getOurInstance().getDaoSession().getChatInformationDao().insert(new ChatInformation(username, 1, messege));

                    }
                });
            }

            @Override
            public void onError(int i, String s) {
            }

            @Override
            public void onProgress(int i, String s) {
            }
        });
    }
    //给好友列表赋值
    private void init() {
        data = new ArrayList<>();
        QueryBuilder qb = AllSingleTon.getOurInstance().getDaoSession().getContactsEntityDao().queryBuilder();
        qb.where(ContactsEntityDao.Properties.User_name_key.eq(EMChatManager.getInstance().getCurrentUser()));
        if (qb != null && qb.list().size() > 0) {
            ArrayList<ContactsEntity> datas = (ArrayList<ContactsEntity>) qb.list();
            friendNames = new ArrayList<>();
            for (int i = 0; i < datas.size(); i++) {
                friendNames.add(datas.get(i).getName());
            }
            String[] arg = new String[friendNames.size()];
            for (int i = 0; i < friendNames.size(); i++) {
                arg[i] = friendNames.get(i);
            }
            data = (ArrayList<SortModel>) filledData(arg);
        }
    }


}
